﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Little_Tower_Defense.Controller;
using Little_Tower_Defense.Interfaces;
using Little_Tower_Defense.Utilitys;

namespace Little_Tower_Defense
{
    /// <summary>
    /// A component to pann a level while holding down the left mouse button.
    /// </summary>
    class LeftMouseButtonPanning : GameComponent, IClickable, IMouseControl
    {
        public new LittleTowerDefense Game;

        private MouseState leftButtonDownMouseState;
        private bool isLeftMouseButtonDown;
        private Level level;

        public LeftMouseButtonPanning(LittleTowerDefense game)
            : base(game)
        {
            this.Game = game;
        }

        public override void Initialize()
        {
            base.Initialize();

            searchNeededComponents();
            isLeftMouseButtonDown = false;
            MouseController.AddListener(this);
        }

        private void searchNeededComponents()
        {
            try
            {
                this.level = (Level)Game.Components.First(a => a is Level);
            }
            catch (NullReferenceException)
            {
                // this is ok, maybe the component will be added later ..
                Logger.WriteLog("ComponentNotFound", "A LeftmouseButtonPanning Instance searched for a Level Instance.");
            }
        }

        public override void Update(GameTime gameTime)
        {
            if (Game.IsActive == true)
            {
                if (isLeftMouseButtonDown)
                {
                    try
                    {
                        MouseState newMouseState = Mouse.GetState();
                        level.OffsetX += newMouseState.X - leftButtonDownMouseState.X;
                        level.OffsetY += newMouseState.Y - leftButtonDownMouseState.Y;
                        leftButtonDownMouseState = newMouseState;
                    }
                    catch (NullReferenceException)
                    {
                        searchNeededComponents();
                    }
                }
            }
        }

        Rectangle Interfaces.IMouseControl.GetArea()
        {
            return (level.Area);
        }

        void IClickable.Click(MouseState state)
        {
            leftButtonDownMouseState = state;
            isLeftMouseButtonDown = true;
        }

        void IClickable.Release()
        {
            isLeftMouseButtonDown = false;
        }
    }
}
